// Package cobramigrate 定义 init子命令，用于初始化数据库
package cobramigrate

import (
	"fmt"
	"github.com/spf13/cobra"
	"tyjt-ferry/database"
	"tyjt-ferry/database/orm"
	"tyjt-ferry/internal/config"
	"tyjt-ferry/internal/models/gorm"
	"tyjt-ferry/pkg/logger"
)

var (
	configPath string
	mode       string
	StartCmd   = &cobra.Command{
		Use:   "init",
		Short: "initialize the databases",
		Run: func(cmd *cobra.Command, args []string) {
			run()
		},
	}
)

func init() {
	// StartCmd 命令添加一个持久标志（Persistent Flag）
	// 把解析后的值赋值给configPath,
	StartCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "config/config.yaml", "Start server with provided configuration file")
	StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
}

func run() {
	usage := `start init`
	fmt.Println(usage)
	// 读取数据库配置
	config.ConfigSetup(configPath)

	// 初始化数据库链接
	database.Setup()

	// 数据库迁移
	migrateModel()
	logger.Info("数据库结构初始化成功！")
	fmt.Println("数据库结构初始化成功！")
}

func migrateModel() error {
	if config.DataBaseConfig.Dbtype == "mysql" {
		orm.Eloquent = orm.Eloquent.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
	}
	return gorm.AutoMigrate(orm.Eloquent)
}
